/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.techshop.controller;

import com.techshop.model.District;
import com.techshop.model.Province;
import com.techshop.model.Store;
import com.techshop.service.DistrictService;
import com.techshop.service.ProvinceService;
import com.techshop.service.StoreService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Hai-PC
 */
@ManagedBean(name = "storeController")
@ViewScoped
public class StoreController extends AbstractController
{
    Store selectedStore;
    Store selectedStoreComplete = new Store();
    List<Store> storeList;
    List<Store> filterStores;
    
    private Province selectedProvince = new Province();
    private District selectedDistrict = new District();
    private List<Province> provinceList;
    private List<District> districtList;
    private List<District> updateDistrictList;
    
    @ManagedProperty(value = "#{storeService}")
    StoreService storeService;
    @ManagedProperty(value = "#{provinceService}")
    private ProvinceService provinceService;
    @ManagedProperty(value = "#{districtService}")
    private DistrictService districtService;
    
    private boolean isSearch = false;
    
    @PostConstruct
    public void init()
    {
        selectedStore = new Store();
        selectedStore.setProvince(new Province());
        selectedStore.setDistrict(new District());
    }
    
    public void insert()
    {
        isSearch = false;
        if (!filePath.isEmpty())
        {
            selectedStore.setImage(filePath);
        }
        selectedStore.setDistrict(selectedDistrict);
        selectedStore.setProvince(selectedProvince);
        if (getStoreService().insert(selectedStore))
        {
            addInfoMessage("Thêm thành công");
        }
        else
        {
            addErrorMessage("Thêm thất bại");
        }
    }

    public void resetFilePath()
    {
        filePath = "";
    }
    
    public void update()
    {
        isSearch = false;
        if (!filePath.isEmpty())
        {
            ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
            File result = new File(extContext.getRealPath(selectedStore.getImage()));
            result.delete();
            selectedStore.setImage(filePath);
        }
        if (getStoreService().update(getSelectedStore()))
        {
            addInfoMessage("Cập nhật thành công");
        }
        else
        {
            addErrorMessage("Cập nhật thất bại");
        }
    }

    public void delete()
    {
        isSearch = false;
        if (getStoreService().delete(getSelectedStore()))
        {
            if (selectedStore.getImage() != null)
            {
                ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
                File result = new File(extContext.getRealPath(selectedStore.getImage()));
                result.delete();
            }
            addInfoMessage("Xóa thành công");
        }
        else
        {
            addErrorMessage("Xóa thất bại");
        }
    }
    
    public void search()
    {
        isSearch = true;
        if (selectedProvince.getId() == 0)
        {
            setStoreList(storeService.getAll());
        }
        else
        {
            if (selectedDistrict.getId() == 0)
            {
                setStoreList(storeService.getByProvince(selectedProvince.getId()));
            }
            else
            {
                if (selectedStore.getId() == 0)
                {
                    setStoreList(storeService.getByProvinceAndDistrict(selectedProvince.getId(), selectedDistrict.getId()));
                }
                else
                {
                    setStoreList(storeService.getByProvinceAndDistrictAndStore(selectedProvince.getId(), selectedDistrict.getId(), selectedStore.getId()));
                }
            }
        }
    }
    
    public void searchStore()
    {
        isSearch = true;
        storeList.clear();
        if (selectedStoreComplete.getId() != null)
        {
            storeList.add(storeService.getById(selectedStoreComplete.getId()));
        }
        else
        {
            setStoreList(storeService.getAll());
        }
    }

    public void resetSelectedStore()
    {
        selectedStore = new Store();
    }

    /**
     * @return the storeList
     */
    public List<Store> getStoreList()
    {
        if (!isSearch)
        {
            setStoreList(getStoreService().getAll());
        }
        return storeList;
    }

    /**
     * @param storeList the storeList to set
     */
    public void setStoreList(List<Store> storeList)
    {
        this.storeList = storeList;
    }

    /**
     * @return the storeService
     */
    public StoreService getStoreService()
    {
        return storeService;
    }

    /**
     * @param storeService the storeService to set
     */
    public void setStoreService(StoreService storeService)
    {
        this.storeService = storeService;
    }
    
    /**
     * @return the selectedStore
     */
    public Store getSelectedStore()
    {
        return selectedStore;
    }

    /**
     * @param selectedStore the selectedStore to set
     */
    public void setSelectedStore(Store selectedStore)
    {
        this.selectedStore = selectedStore;
    }
    
    /**
     * @return the filterStores
     */
    public List<Store> getFilterStores()
    {
        setFilterStores(storeService.getByProvinceAndDistrict(selectedProvince.getId(), selectedDistrict.getId()));
        return filterStores;
    }

    /**
     * @param filterStores the filterStores to set
     */
    public void setFilterStores(List<Store> filterStores)
    {
        this.filterStores = filterStores;
    }
    
    public List<Store> completeStore(String query)
    {
        setStoreList(storeService.getAll());
        List<Store> suggestions = new ArrayList<>();
        for (Store s : storeList)
        {
            if (s.getName().startsWith(query))
            {
                suggestions.add(s);
            }
        }
        return suggestions;
    }

    public Province getSelectedProvince() {
        return selectedProvince;
    }

    public void setSelectedProvince(Province selectedProvince) {
        this.selectedProvince = selectedProvince;
    }

    public District getSelectedDistrict() {
        return selectedDistrict;
    }

    public void setSelectedDistrict(District selectedDistrict) {
        this.selectedDistrict = selectedDistrict;
    }

    public ProvinceService getProvinceService() {
        return provinceService;
    }

    public void setProvinceService(ProvinceService provinceService) {
        this.provinceService = provinceService;
    }

    public DistrictService getDistrictService() {
        return districtService;
    }

    public void setDistrictService(DistrictService districtService) {
        this.districtService = districtService;
    }
    
    public List<Province> getProvinceList() {
        setProvinceList(provinceService.getAll());
        return provinceList;
    }

    public void setProvinceList(List<Province> provinceList) {
        this.provinceList = provinceList;
    }
    
    public List<District> getDistrictList() {
        setDistrictList(districtService.getByProvinceId(selectedProvince.getId()));
        return districtList;
    }

    public void setDistrictList(List<District> districtList) {
        this.districtList = districtList;
    }
    
    public List<District> getUpdateDistrictList() {
        setUpdateDistrictList(districtService.getByProvinceId(selectedStore.getProvince().getId()));
        return updateDistrictList;
    }

    public void setUpdateDistrictList(List<District> updateDistrictList) {
        this.updateDistrictList = updateDistrictList;
    }

    public Store getSelectedStoreComplete() {
        return selectedStoreComplete;
    }

    public void setSelectedStoreComplete(Store selectedStoreComplete) {
        this.selectedStoreComplete = selectedStoreComplete;
    }
    
    public void handleFileUpload(FileUploadEvent event) throws IOException
    {
        //Primitives
        final int BUFFER_SIZE = 6124;
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        // Get categoryId
        String folderToUpload = "//resources//images//store//";
        (new File(extContext.getRealPath(folderToUpload))).mkdirs();       

        
        filePath = folderToUpload + event.getFile().getFileName();
        File result = new File(extContext.getRealPath(filePath));
        System.out.println(extContext.getRealPath(filePath));

        try
        {
            InputStream inputStream;
            try (FileOutputStream fileOutputStream = new FileOutputStream(result))
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int bulk;
                inputStream = event.getFile().getInputstream();
                while (true)
                {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0)
                    {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
            }
            inputStream.close();

            addInfoMessage("file name: " + event.getFile().getFileName() + 
                    "file size: " + event.getFile().getSize() / 1024 + " Kb content type: " + 
                    event.getFile().getContentType() + "The file was uploaded.");
            
            filePath = "//resources//images//store//" + event.getFile().getFileName();
        }
        catch (IOException e)
        {
            System.out.printf("Error :", e.toString());
            addErrorMessage("The files were not uploaded!");
        }
    }
    
    private String filePath = "";
    
    
}